import React, {Component} from 'react';
import {
    Button,
    Card,
    Table,
    Modal,
    Radio,
    Form,
    Input,
    InputNumber,
    message,
    notification,
    Select
} from "antd";
import XLSX from 'xlsx'
import moment from "moment";
import {getUsedCars, getPirce} from "../../api/car";
import {getUsedUsers} from "../../api/user";
import {getLease, deleteLease} from "../../api/lease";
import {addOrder} from "../../api/order";
import { connect} from 'react-redux'
import {getNotifications} from "../../actions/notification";

const mapStateToProps = (state,props) => {
    return {
    }
}

const mapDispatchToProps = (dispatch,props) => {
    return {
        getNotification: () => {
            getNotifications(dispatch)
        }
    }
}

const {Option} = Select;

@connect(mapStateToProps,mapDispatchToProps)

class Index extends Component {
    constructor(props){
        super(props);
        this.addFormRef = React.createRef();
        this.formEditRef = React.createRef();
        this.moneyRef = React.createRef();
        this.state = {
            total: 0,
            pageSize: 6,
            current: 1,
            pageSizeOptions: [6,8,10,12,14],
            loading: false,
            confirmLoading: false,
            selectUserLoading: false,
            selectCarLoading: false,
            deleteIsVisible: false,
            deleteId: '',
            editIsVisible: false,
            editId: '',
            price: 0,
            userValue: '',
            carValue: '',
            addIsVisible: false,
            carsIdList: [],
            usersIdList: [],
            dataSource: [],
            columns: [
                {
                    title: '序号',
                    dataIndex: 'index',
                    key: 'index'
                },
                {
                    title: '名字',
                    dataIndex: 'name',
                    key: 'name'
                },
                {
                    title: "身份证",
                    dataIndex: 'identity',
                    key: 'identity',
                },
                {
                    title: '个人电话',
                    dataIndex: 'iphone',
                    key: 'iphone',
                },
                {
                    title: '车牌号',
                    dataIndex: 'carNumber',
                    key: 'carNumber'
                },
                {
                    title: '租赁时间',
                    dataIndex: 'time',
                    key: 'time'
                },
                {
                    title: '租金',
                    dataIndex: 'money',
                    key: 'money'
                },
                {
                    title: '操作',
                    key: 'action',
                    render: (text,record,index) => {
                        return <Radio.Group size='default'>
                            <Button value='delete' onClick={this.deleteLease.bind(this,{text,record,index})} type='primary'>删除</Button>
                        </Radio.Group>;
                    }
                }
            ],
            layout: {
                labelCol: {
                    span: 6,
                },
                wrapperCol: { span: 12 },
            },
            tailLayout: {
                wrapperCol: { span: 6, offset: 6},
            }
        }
    }

    //导出汽车管理员excel表格
    /*
    *  导出excel表格，一般都是由后端处理了
    *  前端发送ajax请求数据，后端进行数据处理
    * */
    toExcel = () => {
        let leaseExcel = [];
        const leaseKeys = this.state.columns.slice(1,this.state.columns.length - 1).map(item => item.title);
        leaseKeys.unshift('汽车编号');
        leaseKeys.unshift('用户编号');
        leaseKeys.unshift('序号');
        leaseExcel.push(leaseKeys)
        for (let i of this.state.dataSource){
            let {index,userId,carId, name, identity, iphone, carNumber, time, money} = i;
            leaseExcel.push([index,userId,carId, name, identity, iphone, carNumber, time, money]);
        }
        if (this.state.columns.length === 0){
            notification.open({
                message: 'excel打印失败',
                description:
                    '暂时没有列表数据',
                onClick: () => {
                    console.log('点击事件');
                },
            });
            return ;
        }
        const ws = XLSX.utils.aoa_to_sheet(leaseExcel);
        const wb = XLSX.utils.book_new();
        XLSX.utils.book_append_sheet(wb, ws, "SheetJS");
        XLSX.writeFile(wb, `leaseList-${this.state.current}-${moment().format('YYYY-MM-DD h:mm:ss')}.xlsx`)
    }

    //添加租赁信息
    addLease = async () => {
        await this.setState({
            addIsVisible: true,
        })
        await getUsedCars().then(res => {
            const data = res.data;
            this.setState({
                carsIdList: data.map(item => {
                    return item.id;
                })
            })
        })
        await getUsedUsers().then(res => {
            const data = res.data;
            this.setState({
                usersIdList: data.map(item => item.id)
            })
        })
    }

    //页码改变的回调
    paginationChange = (current,pageSize) => {
        this.setState({
            current,
            pageSize: pageSize
        })
    }

    //每页条数改变的回调
    onShowSizeChange = (current, size) => {
        this.setState({
            current: 1,
            pageSize: size
        })
    }

    //删除汽车管理员信息
    deleteLease = ({text,record,index}) => {
        /*this.setState({
            deleteId: record.key,
            deleteName: record.name,
            deleteIsVisible: true
        })*/
        console.log(record)
        deleteLease({userId:record.userId,carId: record.carId}).then(res => {
            message.success(res.msg);
            this.init()
        }).catch(err => {
            message.error(err)
        })
    }

    //添加取消
    addCancel = () => {
        this.setState({
            addIsVisible: false,
        })
    }

    //添加确定
    addOk = () => {
        this.setState({
            confirmLoading: true
        })
        const data = this.addFormRef.current.getFieldsValue();
        addOrder(data).then(res => {
            message.success(res.msg);
            this.addFormRef.current.setFieldsValue({
                userId: '',
                carId: '',
                time: '',
                money: ''
            })
            this.init();
            this.props.getNotification();
        }).catch(err => {
            this.setState({
                confirmLoading: false
            })
        }).finally(() => {
            console.log(1)
            this.setState({
                confirmLoading: false,
                addIsVisible: false,
                userValue: '',
                carValue: '',
                usersIdList: [],
                carsIdList: []

            })
        })
    }

    userOnChange = (value) => {
        this.setState({
            userValue: value
        })
        this.addFormRef.current.setFieldsValue({
            userId: value
        })
    }

    carOnChange = (value) => {
        this.setState({
            carValue: value
        })
        this.addFormRef.current.setFieldsValue({
            carId: value,
            time: '',
            money: ''
        })
        getPirce({carId: value}).then(res => {
            this.setState({
                price: res.data.price
            })
        })
    }

    changeTime = (e) => {
        this.addFormRef.current.setFieldsValue({
            money: e ? Math.ceil(e * this.state.price) : ''
        })
    }


    //初始化数据
    init = () => {
        getLease().then(res => {
            const dataSource = res.data.length ? res.data.map((item,index) => {
                return {
                    index,
                    key: index,
                    userId: item.userId,
                    carId: item.carId,
                    name: item.name,
                    identity: item.identity,
                    iphone: item.iphone,
                    time: item.time,
                    money: item.money,
                    carNumber: item.carNumber
                }
            }): [];
            this.setState({
                dataSource,
                total: res.data.length
            })
        })
    }

    componentDidMount() {
        this.init();
    }

    render() {
        return (
            <Card title="租赁管理" className='mod_card' extra={<span><Button onClick={this.addLease} type='primary' style={{marginRight: 10}}>添加</Button><Button type='primary' shape="round" onClick={this.toExcel}>Excel导出</Button></span>}>
                <Table
                    dataSource={this.state.dataSource}
                    columns={this.state.columns}
                    pagination={{
                        total: this.state.total,
                        pageSize: this.state.pageSize,
                        showSizeChanger: true,
                        pageSizeOptions: this.state.pageSizeOptions,
                        showQuickJumper: true,
                        current: this.state.current,
                        onChange: this.paginationChange,
                        onShowSizeChange: this.onShowSizeChange
                    }}
                    loading={this.state.loading}
                />
                <Modal
                    visible={this.state.addIsVisible}
                    title="添加租赁信息"
                    confirmLoading={this.state.confirmLoading}
                    maskClosable={false}
                    okText="确定添加"
                    cancelText="取消"
                    onCancel={this.addCancel}
                    onOk={this.addOk}
                >
                    <Form
                        {...this.state.layout}
                        name="add_lease"
                        className="add_lease"
                        ref={this.addFormRef}
                        initialValues={{ remember: true }}
                    >
                        <Form.Item
                            label="用户编号"
                            name="userId"
                        >
                            <div>
                                <Select onChange={this.userOnChange} allowClear={true} value={this.state.userValue} style={{ width: 120 }} key='users' loading={this.state.selectUserLoading}>
                                    {
                                        this.state.usersIdList.map(item => {
                                            return <Option value={item} key={item}>{item}</Option>
                                        })
                                    }
                                </Select>
                            </div>
                        </Form.Item>
                        <Form.Item
                            label="汽车编号"
                            name="carId"
                        >
                            <div>
                                <Select onChange={this.carOnChange} style={{ width: 120 }} value={this.state.carValue} key='cars' loading={this.state.selectCarLoading}>
                                    {
                                        this.state.carsIdList.map(item => {
                                            return <Option value={item} key={item}>{item}</Option>
                                        })
                                    }
                                </Select>
                            </div>
                        </Form.Item>
                        <Form.Item
                            label="租赁时间"
                            name="time"
                        >
                            <InputNumber onChange={this.changeTime}/>
                        </Form.Item>
                        <Form.Item
                            label="租金"
                            name="money"
                        >
                            <Input prefix="￥" ref={this.moneyRef} suffix="RMB" disabled={true}/>
                        </Form.Item>
                    </Form>
                </Modal>
            </Card>
        );
    }
}

export default Index;